package com.yc.testupload.controller;

import com.google.gson.Gson;
import com.yc.testupload.dao.AccountDAO;
import com.yc.testupload.model.Account;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 账号保存Servlet
 * 处理账号关系的保存操作
 */
@WebServlet("/api/accounts/save")
public class AccountSaveServlet extends HttpServlet {
    private static final Logger logger = LogManager.getLogger(AccountSaveServlet.class);
    private AccountDAO accountDAO;
    private Gson gson;

    @Override
    public void init() throws ServletException {
        super.init();
        accountDAO = new AccountDAO();
        gson = new Gson();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 设置响应类型为JSON
        response.setContentType("application/json; charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        try {
            // 从session中获取当前登录用户的userId
            HttpSession session = request.getSession(false);
            if (session == null || session.getAttribute("userId") == null) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("error", "用户未登录");
                gson.toJson(errorResponse, response.getWriter());
                return;
            }

            // 获取userId
            Integer userId = Integer.valueOf(session.getAttribute("userId").toString());
            logger.debug("从session获取userId: {}", userId);

            // 确保userId不为null
            if (userId == null) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("error", "无法获取用户信息");
                gson.toJson(errorResponse, response.getWriter());
                return;
            }

            // 解析请求体中的账号关系数据
            AccountRelationRequest relationRequest = gson.fromJson(request.getReader(), AccountRelationRequest.class);

            // 创建Account对象并设置属性
            Account account = new Account();
            account.setUserId(userId);
            account.setAccountType(relationRequest.getAppType().equals("wechat") ? "1" : relationRequest.getAppType()); // 微信类型设置为1
            account.setAccountId(relationRequest.getAppId());
            account.setAccountName(relationRequest.getAccountName());
            account.setAppSecret(relationRequest.getAppSecret()); // 设置AppSecret
            logger.debug("设置AppSecret，长度: {}",
                    relationRequest.getAppSecret() != null ? relationRequest.getAppSecret().length() : 0);

            // 添加账号到数据库
            boolean success = accountDAO.addAccount(account);

            if (success) {
                response.setStatus(HttpServletResponse.SC_OK);
                Map<String, Object> successResponse = new HashMap<>();
                successResponse.put("code", 0);
                successResponse.put("message", "账号关系保存成功");
                gson.toJson(successResponse, response.getWriter());
                logger.info("用户{}成功保存账号关系: {}", userId, relationRequest.getAccountName());
            } else {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("code", 1);
                errorResponse.put("message", "账号关系保存失败");
                gson.toJson(errorResponse, response.getWriter());
                logger.error("用户{}保存账号关系失败: {}", userId, relationRequest.getAccountName());
            }
        } catch (Exception e) {
            logger.error("保存账号关系时出错: {}", e.getMessage(), e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 1);
            errorResponse.put("message", "服务器内部错误: " + e.getMessage());
            gson.toJson(errorResponse, response.getWriter());
        }
    }

    /**
     * 账号关系请求参数类
     */
    private static class AccountRelationRequest {
        private String appId;
        private String accountName;
        private String appType;
        private String appSecret;

        public String getAppId() {
            return appId;
        }

        public void setAppId(String appId) {
            this.appId = appId;
        }

        public String getAccountName() {
            return accountName;
        }

        public void setAccountName(String accountName) {
            this.accountName = accountName;
        }

        public String getAppType() {
            return appType;
        }

        public void setAppType(String appType) {
            this.appType = appType;
        }

        public String getAppSecret() {
            return appSecret;
        }

        public void setAppSecret(String appSecret) {
            this.appSecret = appSecret;
        }
    }
}